package com.wxscrmplus.web.controller.marketing;

import cn.dev33.satoken.annotation.SaIgnore;

import java.util.Collections;
import java.util.List;
import java.util.Arrays;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.wxscrmplus.common.enums.QueryDataRange;
import com.wxscrmplus.common.exception.ServiceException;
import com.wxscrmplus.common.utils.ServletUtils;
import com.wxscrmplus.marketing.domain.MarCategory;
import com.wxscrmplus.marketing.domain.MarMsgAttachments;
import com.wxscrmplus.marketing.domain.bo.MarMsgAttachmentsBo;
import com.wxscrmplus.marketing.domain.bo.MarCategoryBo;
import com.wxscrmplus.marketing.domain.vo.MarMsgAttachmentsVo;
import com.wxscrmplus.marketing.domain.vo.MarCategoryVo;
import com.wxscrmplus.marketing.mapper.MarBatchSendMsgMapper;
import com.wxscrmplus.marketing.service.IMarMsgAttachmentsService;
import com.wxscrmplus.marketing.service.IMarCategoryService;
import com.wxscrmplus.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;

import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.wxscrmplus.common.annotation.RepeatSubmit;
import com.wxscrmplus.common.annotation.Log;
import com.wxscrmplus.common.core.controller.BaseController;
import com.wxscrmplus.common.core.domain.PageQuery;
import com.wxscrmplus.common.core.domain.R;
import com.wxscrmplus.common.core.validate.AddGroup;
import com.wxscrmplus.common.core.validate.EditGroup;
import com.wxscrmplus.common.enums.BusinessType;
import com.wxscrmplus.common.utils.poi.ExcelUtil;
import com.wxscrmplus.marketing.domain.vo.MarBatchSendMsgVo;
import com.wxscrmplus.marketing.domain.bo.MarBatchSendMsgBo;
import com.wxscrmplus.marketing.service.IMarBatchSendMsgService;
import com.wxscrmplus.common.core.page.TableDataInfo;

/**
 * 群发消息
 *
 * @author 王永超
 * @date 2023-05-11
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/marketing/batchSendMsg")
public class MarBatchSendMsgController extends BaseController {
    private final ISysUserService userService;

    private final IMarBatchSendMsgService iMarBatchSendMsgService;
    private final MarBatchSendMsgMapper marBatchSendMsgMapper;
    private final IMarCategoryService iMarCategoryService;
    private final IMarMsgAttachmentsService iMarMsgAttachmentsService;

    /**
     * 回显群发消息选择器值
     *
     * @param batchSendMsgIds 主键串
     */
    @SaIgnore
    @GetMapping("/echoSelect/{batchSendMsgIds}")
    public R<List<MarBatchSendMsgVo>> echoSelect(@NotEmpty(message = "主键不能为空")
                                                 @PathVariable Long[] batchSendMsgIds) {
        List<MarBatchSendMsgVo> list = marBatchSendMsgMapper.selectVoBatchIds(Arrays.asList(batchSendMsgIds));
        return R.ok(list);
    }

    /**
     * 查询群发消息全部数据列表
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:listAll"}, mode = SaMode.OR)
    @GetMapping("/listAll")
    public TableDataInfo<MarBatchSendMsgVo> listAll(MarBatchSendMsgBo bo) {
        return TableDataInfo.build(iMarBatchSendMsgService.queryList(bo));
    }

    /**
     * 查询群发消息列表
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:list"}, mode = SaMode.OR)
    @GetMapping("/list")
    public TableDataInfo<MarBatchSendMsgVo> list(MarBatchSendMsgBo bo, PageQuery pageQuery) {
        List<Long> dataRangeUserIds = Collections.singletonList(getUserId());
        String queryDataRange = ServletUtils.getParameter("queryDataRange");
        if (StrUtil.isNotBlank(queryDataRange)) {
            if (queryDataRange.equals(QueryDataRange.BENBUMENDE.getValue())) {
                StpUtil.checkPermission("marketing:batchSendMsg:list:dept");
                dataRangeUserIds = getDeptUserIds();
            } else if (queryDataRange.equals(QueryDataRange.SUOYOUDE.getValue())) {
                StpUtil.checkPermission("marketing:batchSendMsg:list:all");
                dataRangeUserIds = getAllUserIds();
            }
        }
        bo.setDataRangeUserIds(dataRangeUserIds);
        return iMarBatchSendMsgService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出群发消息列表
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:export"}, mode = SaMode.OR)
    @Log(title = "群发消息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(MarBatchSendMsgBo bo, HttpServletResponse response) {
        List<MarBatchSendMsgVo> list = iMarBatchSendMsgService.queryList(bo);
        ExcelUtil.exportExcel(list, "群发消息", MarBatchSendMsgVo.class, response);
    }

    /**
     * 发送群发消息详细信息
     *
     * @param batchSendMsgId 主键
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:send"}, mode = SaMode.OR)
    @GetMapping("/send/{batchSendMsgId}")
    public R<Void> send(@NotNull(message = "主键不能为空")
                        @PathVariable Long batchSendMsgId) {
        iMarBatchSendMsgService.send(batchSendMsgId);
        return R.ok();
    }

    /**
     * 获取群发消息详细信息
     *
     * @param batchSendMsgId 主键
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:query", "marketing:batchSendMsg:edit"}, mode = SaMode.OR)
    @GetMapping("/{batchSendMsgId}")
    public R<MarBatchSendMsgVo> getInfo(@NotNull(message = "主键不能为空")
                                        @PathVariable Long batchSendMsgId) {
        return R.ok(iMarBatchSendMsgService.queryById(batchSendMsgId));
    }

    /**
     * 新增群发消息
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:add"}, mode = SaMode.OR)
    @Log(title = "群发消息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody MarBatchSendMsgBo bo) {
        bo.setUserId(getUserId());
        if (!userService.checkUserNameIsQwUserId(getUsername())) {
            throw new ServiceException("非企微成员，不可创建");
        }
        return toAjax(iMarBatchSendMsgService.insertByBo(bo));
    }

    /**
     * 修改群发消息
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:edit"}, mode = SaMode.OR)
    @Log(title = "群发消息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody MarBatchSendMsgBo bo) {
        return toAjax(iMarBatchSendMsgService.updateByBo(bo));
    }

    /**
     * 删除群发消息
     *
     * @param batchSendMsgIds 主键串
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:remove"}, mode = SaMode.OR)
    @Log(title = "群发消息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{batchSendMsgIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] batchSendMsgIds) {
        return toAjax(iMarBatchSendMsgService.deleteWithValidByIds(Arrays.asList(batchSendMsgIds), true));
    }


    //-----------------------分类---------------------------

    /**
     * 查询分类管理列表
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:list", "marketing:batchSendMsg:category:listAll"}, mode = SaMode.OR)
    @GetMapping("/category/listAll")
    public R<List<MarCategoryVo>> listAllCategory(MarCategoryBo bo) {
        bo.setCategoryType(MarCategory.CategoryTypeFieldEnums.QUNFARENWU.getValue());
        List<MarCategoryVo> list = iMarCategoryService.queryList(bo);
        return R.ok(list);
    }

    /**
     * 查询分类管理列表
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:category:list"}, mode = SaMode.OR)
    @GetMapping("/category/list")
    public R<List<MarCategoryVo>> listCategory(MarCategoryBo bo) {
        bo.setCategoryType(MarCategory.CategoryTypeFieldEnums.QUNFARENWU.getValue());
        List<MarCategoryVo> list = iMarCategoryService.queryList(bo);
        return R.ok(list);
    }

    /**
     * 获取分类管理详细信息
     *
     * @param categoryId 主键
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:category:query", "marketing:batchSendMsg:category:edit"}, mode = SaMode.OR)
    @GetMapping("/category/{categoryId}")
    public R<MarCategoryVo> getCategoryInfo(@NotNull(message = "主键不能为空")
                                            @PathVariable Long categoryId) {
        return R.ok(iMarCategoryService.queryById(categoryId));
    }

    /**
     * 新增分类管理
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:category:add"}, mode = SaMode.OR)
    @Log(title = "分类管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/category")
    public R<Void> addCategory(@Validated(AddGroup.class) @RequestBody MarCategoryBo bo) {
        bo.setCategoryType(MarCategory.CategoryTypeFieldEnums.QUNFARENWU.getValue());
        return toAjax(iMarCategoryService.insertByBo(bo));
    }

    /**
     * 修改分类管理
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:category:edit"}, mode = SaMode.OR)
    @Log(title = "分类管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/category")
    public R<Void> editCategory(@Validated(EditGroup.class) @RequestBody MarCategoryBo bo) {
        bo.setCategoryType(MarCategory.CategoryTypeFieldEnums.QUNFARENWU.getValue());
        return toAjax(iMarCategoryService.updateByBo(bo));
    }

    /**
     * 删除分类管理
     *
     * @param categoryIds 主键串
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:category:remove"}, mode = SaMode.OR)
    @Log(title = "分类管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/category/{categoryIds}")
// 6e8d3d86c9ae13f1b5832383aaa772f5
    public R<Void> removeCategory(@NotEmpty(message = "主键不能为空")
                                  @PathVariable Long[] categoryIds) {
        return toAjax(iMarCategoryService.deleteWithValidByIds(Arrays.asList(categoryIds), true));
    }
    //--------------附件管理--------------

    /**
     * 查询消息语附件列表
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:attachments:list"}, mode = SaMode.OR)
    @GetMapping("/attachments/list")
    public TableDataInfo<MarMsgAttachmentsVo> listMsgAttachments(MarMsgAttachmentsBo bo, PageQuery pageQuery) {
        bo.setTargetType(MarMsgAttachments.TargetTypeFieldEnums.TWO.getValue());
        return iMarMsgAttachmentsService.queryPageList(bo, pageQuery);
    }

    /**
     * 获取消息语附件详细信息
     *
     * @param msgAttId 主键
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:attachments:query", "marketing:batchSendMsg:attachments:edit"}, mode = SaMode.OR)
    @GetMapping("/attachments/{msgAttId}")
    public R<MarMsgAttachmentsVo> getMsgAttachmentsInfo(@NotNull(message = "主键不能为空")
                                                        @PathVariable Long msgAttId) {
        return R.ok(iMarMsgAttachmentsService.queryById(msgAttId));
    }

    /**
     * 新增消息语附件
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:attachments:add"}, mode = SaMode.OR)
    @Log(title = "消息语附件", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/attachments")
    public R<Void> addMsgAttachments(@Validated(AddGroup.class) @RequestBody MarMsgAttachmentsBo bo) {
        bo.setTargetType(MarMsgAttachments.TargetTypeFieldEnums.TWO.getValue());
        return toAjax(iMarMsgAttachmentsService.insertByBo(bo));
    }

    /**
     * 修改消息语附件
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:attachments:edit"}, mode = SaMode.OR)
    @Log(title = "消息语附件", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/attachments")
    public R<Void> editMsgAttachments(@Validated(EditGroup.class) @RequestBody MarMsgAttachmentsBo bo) {
        bo.setTargetType(MarMsgAttachments.TargetTypeFieldEnums.TWO.getValue());
        return toAjax(iMarMsgAttachmentsService.updateByBo(bo));
    }

    /**
     * 删除消息语附件
     *
     * @param msgAttIds 主键串
     */
    @SaCheckPermission(value = {"marketing:batchSendMsg:attachments:remove"}, mode = SaMode.OR)
    @Log(title = "消息语附件", businessType = BusinessType.DELETE)
    @DeleteMapping("/attachments/{msgAttIds}")
    public R<Void> removeMsgAttachments(@NotEmpty(message = "主键不能为空")
                                        @PathVariable Long[] msgAttIds) {
        return toAjax(iMarMsgAttachmentsService.deleteWithValidByIds(Arrays.asList(msgAttIds), true));
    }
}
